package com.hyhy.hycloud.uaa.service;

import com.hyhy.hycloud.uaa.LoginAttemptProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.concurrent.TimeUnit;

/**
 * @author Xuegui Yuan
 * @date 2019-02-25
 */
@Service
public class LoginAttemptService {

    private static final String LOGIN_ATTEMPT_REDIS_KEY_PREFIX = "LOGIN:ATTEMPT:";

    @Autowired
    LoginAttemptProperties loginAttemptProperties;

    @Autowired
    RedisTemplate<String, Integer> loginAttemptRestTemplate;

    public void loginSuccess(String key) {
        if (!loginAttemptProperties.isEnable()) {
            return;
        }

        Assert.hasText(key, "'key' must has text");
        loginAttemptRestTemplate.delete(LOGIN_ATTEMPT_REDIS_KEY_PREFIX + key);
    }

    public void loginFailure(String key) {
        if (!loginAttemptProperties.isEnable()) {
            return;
        }

        Assert.hasText(key, "'key' must has text");
        String prefixedKey = LOGIN_ATTEMPT_REDIS_KEY_PREFIX + key;
        int attempts = 0;
        Integer value = loginAttemptRestTemplate.opsForValue().get(prefixedKey);
        if (value != null) {
            attempts = value;
        }
        attempts++;
        loginAttemptRestTemplate.opsForValue().set(prefixedKey, attempts,
                loginAttemptProperties.getWaitTime(), TimeUnit.MINUTES);
    }

    public boolean isLoginFailLimit(String key) {
        if (!loginAttemptProperties.isEnable()) {
            return false;
        }

        Assert.hasText(key, "'key' must has text");
        Integer value = loginAttemptRestTemplate.opsForValue().get(LOGIN_ATTEMPT_REDIS_KEY_PREFIX + key);
        return value != null && value >= loginAttemptProperties.getMaxAttempt();
    }
}
